<template>
    <basic-container>
        <avue-crud :option="option"
                   :table-loading="loading"
                   :data="data"
                   :menuList = "menuList"
                   :customMenuDialogVisible = "customMenuDialogVisible"
                   :permission="permissionList"
                   :before-open="beforeOpen"
                   v-model="form"
                   v-model:search="search"
                   v-model:page="page"
                   ref="crud"
                   @row-update="rowUpdate"
                   @row-save="rowSave"
                   @row-del="rowDel"
                   @search-change="searchChange"
                   @search-reset="searchReset"
                   @selection-change="selectionChange"
                   @current-change="currentChange"
                   @size-change="sizeChange"
                   @on-load="onLoad">
            <template #menu-left>
                <el-button type="danger"
                           size="small"
                           icon="el-icon-delete"
                           plain
                           v-if="permission.service_delete"
                           @click="handleDelete">删 除
                </el-button>
            </template>

            <template #menu="{ size, row, index }">
                <el-button @click="handleMenu(row)"
                           icon="el-icon-setting"
                           text
                           type="primary"
                           :size="size">
                    功能定制
                </el-button>
            </template>
        </avue-crud>

        <template>
            <el-dialog title="服务包配置"
                       v-model="this.customVisible"
                       append-to-body="true"
                       width="40%"
                       :body-style="{ maxHeight: 'calc(100vh - 210px)', overflow: 'auto' }">
                <el-tree :data="this.menuList"
                         show-checkbox
                         node-key="id"
                         ref="tree"
                         :default-checked-keys="this.defaultObj"
                         :props="this.treeProps">
                </el-tree>
                <span slot="footer"
                      class="dialog-footer">
                <el-button @click="this.customVisible = false">取 消</el-button>
                <el-button type="primary"
                           @click="submitMenu">确 定</el-button>
            </span>
            </el-dialog>
        </template>

    </basic-container>
</template>

<script>
import {getList, getDetail, add, update, remove, getServiceMenus,grant,grantServiceMenuTree} from "@/api/tenant/service";
import {mapGetters} from "vuex";
import {baseUrl} from "@/config/env";
import permission from "@/views/util/permission.vue";

export default {
    data() {
        return {
            form: {},
            query: {},
            search: {},
            loading: true,
            customVisible: false,
            customServiceId: "",
            defaultObj: [],
            treeProps: {
                label: "name",
                value: "id",
            },
            page: {
                pageSize: 10,
                currentPage: 1,
                total: 0
            },
            menuList: [],
            selectionList: [],
            option: {
                height: 'auto',
                calcHeight: 210,
                searchShow: true,
                searchMenuSpan: 6,
                tip: false,
                border: true,
                index: true,
                viewBtn: true,
                selection: true,
                column: [
                    {
                        label: "服务ID",
                        prop: "id",
                        rules: [{
                            required: true,
                            message: "请输入",
                            trigger: "blur"
                        }]
                    },
                    {
                        label: "服务名称",
                        prop: "serviceName",
                        rules: [{
                            required: true,
                            message: "请输入",
                            trigger: "blur"
                        }]
                    },
                    {
                        label: "所属租户",
                        prop: "tenantId",
                        type: "tree",
                        dicUrl: baseUrl+"/ucs-system/tenant/select",
                        props: {
                            label: "tenantName",
                            value: "tenantId"
                        },
                        rules: [{
                            required: true,
                            message: "请输入租户ID",
                            trigger: "blur"
                        }]
                    },
                    {
                        label: "发布类型",
                        prop: "serviceType",
                        rules: [{
                            required: true,
                            message: "请输入服务类型，所有人可访问，还是只是授权用户可以使用，授 权用户包括收费用户，只是收费是授 权的前提，是否收费由业务系统实现",
                            trigger: "blur"
                        }]
                    },
                ]
            },
            data: []
        };
    },
    computed: {
        permission() {
            return permission
        },
        ...mapGetters(["permission"]),
        permissionList() {
            return {
                addBtn: this.validData(this.permission.service_add, false),
                viewBtn: this.validData(this.permission.service_view, false),
                delBtn: this.validData(this.permission.service_delete, false),
                editBtn: this.validData(this.permission.service_edit, false),
                customMenuBtn: this.validData(this.permission.service_custom, true)
            };
        },
        ids() {
            let ids = [];
            this.selectionList.forEach(ele => {
                ids.push(ele.id);
            });
            return ids.join(",");
        }
    },
    methods: {
        submitMenu(row){
            console.log("update custom menu");
            const menuList = this.$refs.tree.getCheckedKeys().join(",");
            console.log("use api grant menu"+this.customServiceId);
            grant(this.customServiceId, menuList).then(() => {
                console.log("Yes ,Save OK!")
                this.customVisible = false;
                this.$message({
                    type: "success",
                    message: "操作成功!"
                });
                this.onLoad(this.page);
            });
        },
        rowSave(row, done, loading) {
            add(row).then(() => {
                done();
                this.onLoad(this.page);
                this.$message({
                    type: "success",
                    message: "操作成功!"
                });
            }, error => {
                window.console.log(error);
                loading();
            });
        },
        rowUpdate(row, index, done, loading) {
            update(row).then(() => {
                done();
                this.onLoad(this.page);
                this.$message({
                    type: "success",
                    message: "操作成功!"
                });
            }, error => {
                window.console.log(error);
                loading();
            });
        },
        rowDel(row) {
            this.$confirm("确定将选择数据删除?", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            })
                .then(() => {
                    return remove(row.id);
                })
                .then(() => {
                    this.onLoad(this.page);
                    this.$message({
                        type: "success",
                        message: "操作成功!"
                    });
                });
        },
        handleMenu(row) {
            console.log("now in handle menu:"+row.id);
            grantServiceMenuTree()
                .then(res => {
                    console.log("now get menu list now");
                    this.menuList = res.data.data;
                    return getServiceMenus(row.id)
                        .then(res => {
                            console.log("now view box dialogue:"+row.id);
                            this.defaultObj = res.data.data;
                            this.customVisible = true;
                            this.customServiceId = row.id;
                            console.log(this.defaultObj);
                        }, error => {
                            window.console.log("Get Service Menu Error:"+error);
                            loading();
                        });
                }, error => {
                    window.console.log("Get All Menu Error:"+error);
                    loading();
                });
        },
        handleDelete() {
            if (this.selectionList.length === 0) {
                this.$message.warning("请选择至少一条数据");
                return;
            }
            this.$confirm("确定将选择数据删除?", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            })
                .then(() => {
                    return remove(this.ids);
                })
                .then(() => {
                    this.onLoad(this.page);
                    this.$message({
                        type: "success",
                        message: "操作成功!"
                    });
                    this.$refs.crud.toggleSelection();
                });
        },
        beforeOpen(done, type) {
            if (["edit", "view"].includes(type)) {
                getDetail(this.form.id).then(res => {
                    this.form = res.data.data;
                });
            }
            done();
        },
        searchReset() {
            this.query = {};
            this.onLoad(this.page);
        },
        searchChange(params, done) {
            this.query = params;
            this.page.currentPage = 1;
            this.onLoad(this.page, params);
            done();
        },
        selectionChange(list) {
            this.selectionList = list;
        },
        selectionClear() {
            this.selectionList = [];
            this.$refs.crud.toggleSelection();
        },
        currentChange(currentPage){
            this.page.currentPage = currentPage;
        },
        sizeChange(pageSize){
            this.page.pageSize = pageSize;
        },
        onLoad(page, params = {}) {
            console.log("Onload page now..................")
            this.loading = true;
            getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
                const data = res.data.data;
                this.page.total = data.total;
                this.data = data.records;
                this.loading = false;
                this.selectionClear();
            });
        }
    }
};
</script>

<style>
.el-dialog__body{
    max-height: 70vh;
    overflow-y: auto;
}
</style>
